<?php

session_start(); // Start a session or continue a session if the user is allready logged in

include ('connection.php');

// Some variables that are used throughout the entire website
$cfg['tijd']				= 3600*48; // Tijd in seconden die je krijgt om je account te activeren. 3600 = 1 uur.
$cfg['w_tijd']				= 3600*48; // Tijd in de seconden die je krijgt om je wachtwoord te activeren.
$cfg['site']				= "obstacle.be"; // Sitename
$cfg['url']				= "http://www.obstacle.be/"; // Site-url, inc. slash!!!
$cfg['email']				= "noreply@obstacle.be"; // Sender of the aumotaticly send emails
$cfg['act_lengte']			= 10; // standard-length used in the function activatiecode
$cfg['attempts']			= 3; // amount of times you can try to login before you're send to the page to request a new password
$cfg['basepath']                        = "http://".$_SERVER['HTTP_HOST']."/ObstacleWebApp/"; // basepath

$connection = new createConnection();
$connection->connectToDatabase();
$connection->selectDatabase();

//include('sessie.php');

/**
 * This function checks if the email is a valid email
 */
function check_email($in) {
  $patroon = "/^([a-z0-9_-]+\.)*[a-z0-9_-]+@([a-z0-9_-]{2,}\.)+([a-z0-9_-]{2,})$/i";
  return preg_match($patroon, $in);
} 

/**
 * This function generated a string of a given length of random numbers and letters 
 */
function activatiecode ($lengte) {
  $activatie = "";
  mt_srand ((double) microtime() * 1000000);
  while (strlen($activatie) < $lengte) {
    $kiezen = chr(mt_rand (0,255));
    if (eregi("^[a-zA-Z0-9]$", $kiezen)) $activatie = $activatie.$kiezen;
  }
return ($activatie);
} 

/**
 * This function prepares a string before it's send to the database.
 * It prevents SQL-injection and aids with the stability of the database
 * @param string $in
 * @return string
 */
function PrepareVariable($in)
{
    $temp = mysql_real_escape_string($in);
    return $temp;
}

/**
 * This function returns all the buildings but with a limit for pagination
 * @param int $eu
 * @param int $limit
 * @return resultset resultset with all the buildings
 */
function GetAllBuildingsLimit($eu, $limit)
{
    try {
        $rs = mysql_query("CALL GetAllBuildingsLimit($eu, $limit)") or die (mysql_error());
        return $rs;
    } catch (Exception $exc) {
        echo $exc->getTraceAsString();
    }
}

/**
 * This function returns all the buildings that match the search-criteria but with a limit for pagination
 * @param int $eu
 * @param int $limit
 * @param string $search
 * @return resultset resultset with all the buildings
 */
function GetAllBuildingsLimitWithSearch($eu, $limit, $search)
{
    try {
        $search = PrepareVariable($search);
        $rs = mysql_query("CALL GetAllBuildingsLimitWithSearch($eu, $limit, '$search')") or die (mysql_error());
        return $rs;
    } catch (Exception $exc) {
        echo $exc->getTraceAsString();
    }
}

/**
 * This function returns the number of buildings
 * @return int count of all the buildings
 */
function GetAllBuildingsCount()
{
    try {
        $rs = mysql_query("CALL GetAllBuildingsCount(@number)") or die (mysql_error());
        $rs = mysql_query("SELECT @number");
        while($row = mysql_fetch_assoc($rs))
        {
            return $row['@number'];
        }
    } catch (Exception $exc) {
        echo $exc->getTraceAsString();
    }
}

/**
 * This function returns the number of buildings that match the search-criteria
 * @param string $search
 * @return int count of all the buildings
 */
function GetAllBuildingsCountWithSearch($search)
{
    try {
        $search = PrepareVariable($search);
        $rs = mysql_query("CALL GetAllBuildingsCountWithSearch('$search',@number)") or die (mysql_error());
        $rs = mysql_query("SELECT @number");
        while($row = mysql_fetch_assoc($rs))
        {
            return $row['@number'];
        }
    } catch (Exception $exc) {
        echo $exc->getTraceAsString();
    }
}

/**
 * This function returns a resultset with all the data of one building
 * @param int $id
 * @return ResultSet ResultSet containing all the data of one building
 */
function GetBuildingById($id)
{
    try {
        $rs = mysql_query("CALL GetBuildingById($id, @id, @street, @number, @cityid, @yearofconstruction, @buildingtypeid)") or die (mysql_error());
        $rs = mysql_query("SELECT @id, @street, @number, @cityid, @yearofconstruction, @buildingtypeid");
        return $rs;
    } catch (Exception $exc) {
        echo $exc->getTraceAsString();
    }
}

/**
 * This function returns all the cities ordered by zip-code
 * @return City
 */
function GetAllCityOrderByZIP()
{
    try {
        $queryGetAllCities = "SELECT * FROM City ORDER BY ZIP";
        $resultGetAllCities = mysql_query($queryGetAllCities) or die (mysql_error());
        return $resultGetAllCities;
    } catch (Exception $exc) {
        echo $exc->getTraceAsString();
    }
}

/**
 * This function returns all the building types
 * @return BuildingType
 */
function GetAllBuildingtype()
{
    try {
        $queryGetAllBuildingtypes = "SELECT * FROM BuildingType";
        $resultGetAllBuildingtypes = mysql_query($queryGetAllBuildingtypes) or die (mysql_error());
        return $resultGetAllBuildingtypes;
    } catch (Exception $exc) {
        echo $exc->getTraceAsString();
    }
}

/**
 * This function returns all the building specs
 * @return BuildingSpec
 */
function GetAllBuildingSpecs()
{
    try {
        $queryGetAllBuildingSpecs = "SELECT * FROM BuildingSpec WHERE Activated='T'";
        $resultGetAllBuildingSpecs = mysql_query($queryGetAllBuildingSpecs) or die (mysql_error());
        return $resultGetAllBuildingSpecs;
    } catch (Exception $exc) {
        echo $exc->getTraceAsString();
    }
}

/**
 * This function returns the building's details
 * @param int $buildingid
 * @param int $buildingspecid
 * @return buildingdetail
 */
function GetBuildingDetail($buildingid, $buildingspecid)
{
    try {
        $queryGetBuildingDetail = "SELECT * FROM buildingdetail WHERE BuildingId=$buildingid AND BuildingSpecId=$buildingspecid";
        $resultGetBuildingDetail = mysql_query($queryGetBuildingDetail) or die (mysql_error());
        return $resultGetBuildingDetail;
    } catch (Exception $exc) {
        echo $exc->getTraceAsString();
    }
}

/**
 * This function updates the building's details
 * @param int $buildingid
 * @param string $street
 * @param string $number
 * @param int $cityid
 * @param datetime $yearofconstruction
 * @param building $buildingtypeid
 */
function UpdateBuilding($buildingid, $street, $number, $cityid, $yearofconstruction, $buildingtypeid)
{
    try {
        $street = PrepareVariable($street);
        $number = PrepareVariable($number);
        mysql_query("CALL UpdateBuilding($buildingid, '$street', '$number', $cityid, '$yearofconstruction', $buildingtypeid)") or die (mysql_error());
    } catch (Exception $exc) {
        echo $exc->getTraceAsString();
    }
}

/**
 * This function inserts the building's details
 * @param int $buildingid
 * @param int $buildingspecid
 * @param string $specvalue
 */
function InsertBuildingDetail($buildingid, $buildingspecid, $specvalue)
{
    try {
        $specvalue = PrepareVariable($specvalue);
        mysql_query("CALL InsertBuildingDetail($buildingid, $buildingspecid, '$specvalue')") or die (mysql_error());
    } catch (Exception $exc) {
        echo $exc->getTraceAsString();
    }
}

/**
 * This function updates the building's details
 * @param int $id
 * @param string $specvalue
 */
function UpdateBuildingDetail($id, $specvalue)
{
    try {
        $specvalue = PrepareVariable($specvalue);
        mysql_query("CALL UpdateBuildingDetail($id, '$specvalue')") or die (mysql_error());
    } catch (Exception $exc) {
        echo $exc->getTraceAsString();
    }
}

/**
 * This function deletes building's details
 * @param int $id
 */
function DeleteBuildingDetail($id)
{
    try {
        mysql_query("CALL DeleteBuildingDetail($id)") or die (mysql_error());
    } catch (Exception $exc) {
        echo $exc->getTraceAsString();
    }
}

/**
 * This function returns a city
 * @param int $id
 * @return city
 */
function GetCityById($id)
{
    try {
        $rs = mysql_query("CALL GetCityById($id, @id, @zip, @city)") or die (mysql_error());
        $rs = mysql_query("SELECT @id, @zip, @city");
        return $rs;
    } catch (Exception $exc) {
        echo $exc->getTraceAsString();
    }
}

/**
 * This function returns a building type
 * @param int $id
 * @return buildingtype
 */
function GetBuildingTypeById($id)
{
    try {
        $rs = mysql_query("CALL GetBuildingTypeById($id, @name)") or die (mysql_error());
        $rs = mysql_query("SELECT @name");
        return $rs;
    } catch (Exception $exc) {
        echo $exc->getTraceAsString();
    }
}

/**
 * This function returns a patient's name
 * @param int $buildingid
 * @return patient
 */
function GetPatientByBuildingId($buildingid)
{
    try {
        $rs = mysql_query("CALL GetPatientByBuildingId($buildingid, @id, @firstname, @lastname)") or die (mysql_error());
        $rs = mysql_query("SELECT @id, @firstname, @lastname");
        return $rs;
    } catch (Exception $exc) {
        echo $exc->getTraceAsString();
    }
}

/**
 * This function returns the info of a building
 * @param int $buildingspecid
 * @return ResultSet
 */
function GetBuildingSpecById($buildingspecid)
{
    try {
        $rs = mysql_query("CALL GetBuildingSpecById($buildingspecid, @buildingkey, @required, @comment)") or die (mysql_error());
        $rs = mysql_query("SELECT @buildingkey, @required, @comment");
        return $rs;
    } catch (Exception $exc) {
        echo $exc->getTraceAsString();
    }
}

/**
 * This function updates the activated-status of a building's detail
 * @param int $buildingspecid
 * @param string $activated either T for true or F for false
 * @return int
 */
function UpdateBuildingSpecActivated($buildingspecid, $activated)
{
    try {
        mysql_query("CALL UpdateBuildingSpecActivated($buildingspecid, '$activated')") or die (mysql_error());
        return 1;
    } catch (Exception $exc) {
        echo $exc->getTraceAsString();
    }
}

/**
 * This function updates a building's detail
 * @param id $buildingspecid
 * @param string $buildingkey
 * @param string $required
 * @param string $comment
 */
function UpdateBuildingSpec($buildingspecid, $buildingkey, $required, $comment)
{
    try {
        $buildingkey = PrepareVariable($buildingkey);
        $comment = PrepareVariable($comment);
        mysql_query("CALL UpdateBuildingSpec($buildingspecid, '$buildingkey', '$required', '$comment')") or die (mysql_error());
    } catch (Exception $exc) {
        echo $exc->getTraceAsString();
    }
}

/**
 * This function returns the amount of building specs
 * @return int count of all the buildings
 */
function GetAllBuildingSpecCount()
{
    try {
        $rs = mysql_query("CALL GetAllBuildingSpecCount(@number)") or die (mysql_error());
        $rs = mysql_query("SELECT @number");
        while($row = mysql_fetch_assoc($rs))
        {
            return $row['@number'];
        }
    } catch (Exception $exc) {
        echo $exc->getTraceAsString();
    }
}

/**
 * This function returns all the building specs but with a limit for pagination
 * @param int $eu
 * @param int $limit
 * @return resultset resultset with all the building specs
 */
function GetAllBuildingSpecLimit($eu, $limit)
{
    try {
        $rs = mysql_query("CALL GetAllBuildingSpecLimit($eu, $limit)") or die (mysql_error());
        return $rs;
    } catch (Exception $exc) {
        echo $exc->getTraceAsString();
    }
}

/**
 * This function inserts a building spec
 * @param string $buildingkey
 * @param string $activated
 * @param string $required
 * @param string $comment
 */
function InsertBuildingSpec($buildingkey, $activated, $required, $comment)
{
    try {
        $buildingkey = PrepareVariable($buildingkey);
        $comment = PrepareVariable($comment);
        mysql_query("CALL InsertBuildingSpec('$buildingkey', '$activated', '$required', '$comment')") or die (mysql_error());
    } catch (Exception $exc) {
        echo $exc->getTraceAsString();
    }
}

/**
 * This function inserts a building
 * @param string $street
 * @param string $number
 * @param int $cityid
 * @param date $yearofconstruction
 * @param int $buildingtypeid
 */
function InsertBuilding($street, $number, $cityid, $yearofconstruction, $buildingtypeid)
{
    try {
        $street = PrepareVariable($street);
        $number = PrepareVariable($number);
        $yearofconstruction = PrepareVariable($yearofconstruction);
        mysql_query("CALL InsertBuilding('$street', '$number', $cityid, '$yearofconstruction', $buildingtypeid)") or die (mysql_error());
    } catch (Exception $exc) {
        echo $exc->getTraceAsString();
    }
}

/**
 * This function returns the id of the last building
 * @return int id of the last building
 */
function GetLastBuilding()
{
    try {
        $rs = mysql_query("CALL GetLastBuilding(@id)") or die (mysql_error());
        $rs = mysql_query("SELECT @id");
        while($row = mysql_fetch_assoc($rs))
        {
            return $row['@id'];
        }
    } catch (Exception $exc) {
        echo $exc->getTraceAsString();
    }
}

/**
 * This function returns a user from the database
 * @param int $userid
 * @return user
 */
function GetUserById($userid)
{
    try {
        $rs = mysql_query("CALL GetUserById($userid, @firstname, @lastname, @email, @function, @dayofbirth, @admin)") or die (mysql_error());
        $rs = mysql_query("SELECT @firstname, @lastname, @email, @function, @dayofbirth, @admin");
        return $rs;
    } catch (Exception $exc) {
        echo $exc->getTraceAsString();
    }
}

/**
 * This function returns a resultset with all the possible user functions
 * @return ResultSet ResultSet with all the user functions
 */
function GetAllUserFunctions()
{
    try {
        $rs = mysql_query("CALL GetAllUserFunctions()") or die (mysql_error());
        return $rs;
    } catch (Exception $exc) {
        echo $exc->getTraceAsString();
    }
}

/**
 * This function updates a user's data when no password has been entered
 * @param int $id
 * @param string $username
 * @param string $firstname
 * @param string $lastname
 * @param string $email
 * @param int $function
 * @param datetime $dayofbirth
 * @param string $admin
 */
function UpdateUser($id, $username, $firstname, $lastname, $email, $function, $dayofbirth, $admin)
{
    try {
        $username = PrepareVariable($username);
        $firstname = PrepareVariable($firstname);
        $lastname = PrepareVariable($lastname);
        $email = PrepareVariable($email);
        $dayofbirth = PrepareVariable($dayofbirth);
        mysql_query("CALL UpdateUser($id, '$username', '$firstname', '$lastname', '$email', $function, '$dayofbirth', '$admin')") or die (mysql_error());
    } catch (Exception $exc) {
        echo $exc->getTraceAsString();
    }
}

/**
 * This function updates a user's data when a password has been entered
 * @param int $id
 * @param string $username
 * @param string $firstname
 * @param string $lastname
 * @param string $email
 * @param string $password
 * @param int $function
 * @param datetime $dayofbirth
 * @param string $admin
 */
function UpdateUserPassword($id, $username, $firstname, $lastname, $email, $password, $function, $dayofbirth, $admin)
{
    try {
        $username = PrepareVariable($username);
        $firstname = PrepareVariable($firstname);
        $lastname = PrepareVariable($lastname);
        $email = PrepareVariable($email);
        $password = PrepareVariable($password);
        $dayofbirth = PrepareVariable($dayofbirth);
        mysql_query("CALL UpdateUserPassword($id, '$username', '$firstname', '$lastname', '$email', '$password', $function, '$dayofbirth', '$admin')") or die (mysql_error());
    } catch (Exception $exc) {
        echo $exc->getTraceAsString();
    }
}

/**
 * This funtion activates or deactivates a user
 * @param string $id
 * @param string $activated either T for true or F for false
 * @return int Returns 1 of it was successfull
 */
function UpdateUserActivated($id, $activated)
{
    try {
        mysql_query("CALL UpdateUserActivated($id, '$activated')") or die (mysql_error());
        return 1;
    } catch (Exception $exc) {
        echo $exc->getTraceAsString();
    }
}

/**
 * This function returns the number of users
 * @return int count of all the users
 */
function GetAllUserCount()
{
    try {
        $rs = mysql_query("CALL GetAllUserCount(@number)") or die (mysql_error());
        $rs = mysql_query("SELECT @number");
        while($row = mysql_fetch_assoc($rs))
        {
            return $row['@number'];
        }
    } catch (Exception $exc) {
        echo $exc->getTraceAsString();
    }
}

/**
 * This function returns the number of users
 * @param string $search
 * @return int count of all the users
 */
function GetAllUserCountWithSearch($search)
{
    try {
        $search = PrepareVariable($search);
        $rs = mysql_query("CALL GetAllUserCountWithSearch('$search', @number)") or die (mysql_error());
        $rs = mysql_query("SELECT @number");
        while($row = mysql_fetch_assoc($rs))
        {
            return $row['@number'];
        }
    } catch (Exception $exc) {
        echo $exc->getTraceAsString();
    }
}

/**
 * This function returns all the users but with a limit for pagination
 * @param int $eu
 * @param int $limit
 * @return resultset resultset with all the users
 */
function GetAllUserLimit($eu, $limit)
{
    try {
        $rs = mysql_query("CALL GetAllUserLimit($eu, $limit)") or die (mysql_error());
        return $rs;
    } catch (Exception $exc) {
        echo $exc->getTraceAsString();
    }
}

/**
 * This function returns all the users that match the search-criteria but with a limit for pagination
 * @param int $eu
 * @param int $limit
 * @param string $search
 * @return resultset resultset with all the users
 */
function GetAllUserLimitWithSearch($eu, $limit, $search)
{
    try {
        $search = PrepareVariable($search);
        $rs = mysql_query("CALL GetAllUserLimitWithSearch($eu, $limit, '$search')") or die ("F*cking error: ".mysql_error());
        return $rs;
    } catch (Exception $exc) {
        echo $exc->getTraceAsString();
    }
}

/**
 * This function returns the number of users with a certain email-adress
 * @param string $email
 * @return int count of all the users with a certain email-adress
 */
function GetUserCountByEmail($email)
{
    try {
        $email = PrepareVariable($email);
        $rs = mysql_query("CALL GetUserCountByEmail('$email', @number)") or die (mysql_error());
        $rs = mysql_query("SELECT @number");
        while($row = mysql_fetch_assoc($rs))
        {
            return $row['@number'];
        }
    } catch (Exception $exc) {
        echo $exc->getTraceAsString();
    }
}

/**
 * This function inserts a new user
 * @param string $username
 * @param string $firstname
 * @param string $lastname
 * @param string $password
 * @param string $email
 * @param int $userfunction
 * @param date $dayofbirth
 * @param string $admin
 * @param string $activated
 */
function InsertUser($username, $firstname, $lastname, $password, $email, $userfunction, $dayofbirth, $admin, $activated)
{
    try {
        $username = PrepareVariable($username);
        $firstname = PrepareVariable($firstname);
        $lastname = PrepareVariable($lastname);
        $password = PrepareVariable($password);
        $email = PrepareVariable($email);
        $activated = PrepareVariable($activated);
        $dayofbirth = PrepareVariable($dayofbirth);
        $admin = PrepareVariable($admin);
        mysql_query("CALL InsertUser('$username', '$firstname', '$lastname', '$password', '$email', $userfunction, '$dayofbirth', '$admin', '$activated')") or die (mysql_error());
    } catch (Exception $exc) {
        echo $exc->getTraceAsString();
    }
}

?>